package com.souku.finance.application.ui.borrow;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.manager.RequestManager;
import com.souku.finance.application.R;
import com.souku.finance.application.base.BaseFragment;
import com.souku.finance.application.http.UrlConstact;
import com.souku.finance.application.http.retrofit.RetrofitUtils;
import com.souku.finance.application.http.volley.ReqListener;
import com.souku.finance.application.http.volley.Success;
import com.souku.finance.application.utils.Constant;
import com.souku.finance.application.utils.JsonUtil;
import com.souku.finance.application.utils.ParamUtil;
import com.souku.finance.application.utils.ShareUtil;
import com.souku.finance.application.utils.ToastUtil;
import com.souku.finance.application.utils.ViewUtil;
import com.souku.finance.application.utils.level.LogUtils;
import com.souku.finance.application.utils.level.StringUtils;

import org.json.JSONObject;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Administrator on 2017/5/5 0005.
 */

public class BorrowFragment extends BaseFragment implements View.OnClickListener {

    protected View rootView;

    Unbinder unbinder;

    @BindView(R.id.iv_name)
    ImageView ivName;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.iv_phone)
    ImageView ivPhone;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.iv_money)
    ImageView ivMoney;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.et_money)
    EditText etMoney;
    @BindView(R.id.textView5)
    TextView textView5;
    @BindView(R.id.iv_time)
    ImageView ivTime;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.et_time)
    EditText etTime;
    @BindView(R.id.iv_change_time)
    ImageView ivChangeTime;
    @BindView(R.id.iv_code)
    ImageView ivCode;
    @BindView(R.id.tv_code)
    TextView tvCode;
    @BindView(R.id.et_code)
    EditText etCode;
    @BindView(R.id.btn_recharge)
    Button btnRecharge;
    @BindView(R.id.iv_ver)
    ImageView ivVer;
    @BindView(R.id.btn_code)
    Button btnCode;

    String ivTimeStr = "0";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fra_borrow, container, false);
        unbinder = ButterKnife.bind(this, rootView);
        setContent(rootView);
        return rootView;
    }

    @Override
    public void internet() {

    }

    @Override
    public void showFragment() {

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        btnCode.setOnClickListener(this);

    }

    public void getRecharge() {

        String name = etName.getText().toString();        //名字
        String phone = etPhone.getText().toString();      //手机号码
        String money = etMoney.getText().toString();      //申请金额
        String time = etTime.getText().toString();        //借款期限
        String code = etCode.getText().toString();        //验证码
        String accessToken = ShareUtil.getInstance().getString(Constant.Token);
        String userId = ShareUtil.getInstance().getString(Constant.UserId);

        if (TextUtils.isEmpty(name)) {
            Toast.makeText(getContext(), "请输入姓名", Toast.LENGTH_LONG).show();
            return;
        }
        if (TextUtils.isEmpty(phone)) {
            Toast.makeText(getContext(), "请输入手机号码", Toast.LENGTH_LONG).show();
            return;
        }
        if (TextUtils.isEmpty(money)) {
            Toast.makeText(getContext(), "请输入申请金额", Toast.LENGTH_LONG).show();
            return;
        }
        if (TextUtils.isEmpty(time)) {
            Toast.makeText(getContext(), "请输入借款期限", Toast.LENGTH_LONG).show();
            return;
        }
        if (TextUtils.isEmpty(code)) {
            Toast.makeText(getContext(), "请输入验证码", Toast.LENGTH_LONG).show();
            return;
        }

//        Call<ResponseBody> getMemberBorrow(@Query("accessToken") String accessToken
//                , @Query("userid") String userid
//                , @Query("userName") String userName
//                , @Query("mobile") String mobile
//                , @Query("amount") String amount
//                , @Query("projectRange") String projectRange  期限
//                , @Query("deadLineType") String deadLineType  期限月跟天
//                , @Query("province") String province
//                , @Query("city") String city
//                , @Query("imageVerifyCode") String imageVerifyCode
//                , @Query("fromSource") String fromSource);

//        RetrofitUtils.create(UrlConstact.Base_Url).getMemberBorrow(accessToken, userId, name, phone
//                , money, time, ivTimeStr, "-1"
//                , "-1", code, "wechat").enqueue(new Callback<ResponseBody>() {
//            @Override
//            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
//                try {
//                    JSONObject object = new JSONObject(response.body().string());
//                    if (object.getInt("errorCode") == 1) {
//                        Toast.makeText(getContext(), object.getString("errorMessage"), Toast.LENGTH_LONG).show();
//                        getVer();
//                    } else {
//                        Toast.makeText(getContext(), object.getString("errorMessage"), Toast.LENGTH_LONG).show();
//                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    getVer();
//                }
//            }
//
//            @Override
//            public void onFailure(Call<ResponseBody> call, Throwable t) {
//
//            }
//        });

        RetrofitUtils.create(UrlConstact.Base_Url).getMemberBorrow(name, phone, money,
                ivTimeStr, time, code).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    JSONObject object = new JSONObject(response.body().string());
                    if (object.getInt("code") == 1) {
                        Toast.makeText(getContext(), "申请成功", Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(getContext(), "申请失败", Toast.LENGTH_LONG).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(getContext(), "申请失败", Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    final CountDownTimer timer = new CountDownTimer(60 * 1000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            btnCode.setText(millisUntilFinished / 1000 + "S");
            btnCode.setEnabled(false);
        }

        @Override
        public void onFinish() {
            btnCode.setText("立即获取");
            btnCode.setEnabled(true);
        }
    };

    @OnClick({R.id.iv_ver, R.id.btn_recharge, R.id.iv_change_time, R.id.btn_code})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_ver:
                break;
            case R.id.btn_code:
                String mobile = etPhone.getText().toString().trim();
                if (!StringUtils.isMobileNum(mobile)) {
                    ToastUtil.show("请输入手机号码");
                    return;
                }
                sendCode(mobile);
                btnCode.setEnabled(false);
                timer.start();
                break;
            case R.id.btn_recharge:
                getRecharge();
                break;
            case R.id.iv_change_time:
                if (ivTimeStr.equals("0")) {
                    ivTimeStr = "1";
                    ivChangeTime.setImageResource(R.drawable.yueshang);
                } else {
                    ivTimeStr = "0";
                    ivChangeTime.setImageResource(R.drawable.tianshang);
                }
                break;
        }
    }

    private void sendCode(String mobile) {
        HashMap<String, String> map = ParamUtil.getParams();
        map.put("mobile", mobile);
        RequestManager.getInstance().post(UrlConstact.SEND_MOBILE_CODE, ParamUtil.getSing(map), new ReqListener(getActivity(), new Success() {
            @Override
            public void onSuccess(String response) {
                if (JsonUtil.getCode(response) == 1) {
                    ToastUtil.show("验证码发送成功");
                } else {
                    ToastUtil.show(JsonUtil.getMessage(response));
                }
            }
        }), ParamUtil.getHeaders());
    }

    @Override
    public void onClick(View view) {
        String mobile = etPhone.getText().toString().trim();
        if (!StringUtils.isMobileNum(mobile)) {
            ToastUtil.show("请输入手机号码");
            return;
        }
        sendCode(mobile);
        btnCode.setEnabled(false);
        timer.start();
    }
}
